#!/bin/bash

# HTTPSOK SSL证书管理面板 v3.0
# 作者: 高级工程师
# 功能: SSL证书申请、续签、监控和管理
# 参考: https://httpsok.com/

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m' # No Color

# 项目配置
PROJECT_NAME="httpsok"
PROJECT_VERSION="3.0"
PROJECT_HOME="$HOME/.httpsok"
PROJECT_BACKUPS="$HOME/.httpsok/backups"
PROJECT_LOG_FILE="$PROJECT_HOME/httpsok.log"
PROJECT_TOKEN_FILE="$PROJECT_HOME/token"
PROJECT_UUID_FILE="$PROJECT_HOME/uuid"

# API配置
BASE_API_URL="https://api.httpsok.com/v1/nginx"
SCRIPT_URL="https://get.httpsok.com/"

# 全局变量
HTTPSOK_TOKEN=""
HTTPSOK_UUID=""
NGINX_CONFIG=""
NGINX_CONFIG_HOME=""
NGINX_BIN="nginx"
OS=""
NGINX_VERSION=""
MODE="normal"
TRACE_ID=""
latest_code=""
preparse=""

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 打印标题
print_title() {
    clear
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔒 HTTPS SSL证书管理面板 v${PROJECT_VERSION}${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo
}

# 显示欢迎信息
show_welcome() {
    print_title
    echo -e "${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║${NC}                    ${WHITE}SSL证书自动化管理工具${NC}                     ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}                                                              ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE}支持功能：${NC} ${CYAN}证书申请、自动续签、状态监控${NC}                   ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE}证书类型：${NC} ${CYAN}单域名、多域名、通配符证书${NC}                     ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE}提供商：${NC} ${CYAN}Let's Encrypt、ZeroSSL、Google Trust${NC}             ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE}适用系统：${NC} ${CYAN}CentOS/RHEL/Ubuntu/Debian${NC}                      ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}                                                              ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}                         作者：宋利军                         ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}                         版本：v${PROJECT_VERSION}                           ${GREEN}║${NC}"
    echo -e "${GREEN}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo
}

# 显示简洁欢迎信息（用于命令行模式）
show_simple_welcome() {
    echo
    echo -e "${CYAN}HTTPSOK SSL证书管理面板${NC}     https://httpsok.com/"
    echo -e "${CYAN}版本: $PROJECT_VERSION${NC}"
    echo
}

# 显示主菜单
show_main_menu() {
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}📋 主菜单${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo
    echo -e "${WHITE} 1.${NC} ${CYAN}证书申请${NC}                    ${WHITE} 7.${NC} ${CYAN}DNS 配置${NC}"
    echo -e "${WHITE} 2.${NC} ${CYAN}证书续签${NC}                    ${WHITE} 8.${NC} ${CYAN}系统设置${NC}"
    echo -e "${WHITE} 3.${NC} ${CYAN}证书管理${NC}                    ${WHITE} 9.${NC} ${CYAN}日志查看${NC}"
    echo -e "${WHITE} 4.${NC} ${CYAN}证书下载${NC}                    ${WHITE}10.${NC} ${CYAN}帮助文档${NC}"
    echo -e "${WHITE} 5.${NC} ${CYAN}证书部署${NC}                    ${WHITE}11.${NC} ${CYAN}一键运行${NC}"
    echo -e "${WHITE} 6.${NC} ${CYAN}证书监控${NC}                    ${WHITE}12.${NC} ${CYAN}系统诊断${NC}"
    echo
    echo -e "${WHITE} 0.${NC} ${RED}退出系统${NC}"
    echo
    echo -e "${YELLOW}💡 提示：请输入对应的数字选择功能${NC}"
}

# 创建目录
_mkdirs() {
    local dir="$1"
    if [ ! "$dir" = "" ]; then
        if [ ! -d "$dir" ]; then
            mkdir -p "$dir" && print_message $GREEN "✅ 创建目录: $dir"
        fi
    fi
}

# 初始化路径
_initpath() {
    _mkdirs "$PROJECT_HOME"
    _mkdirs "$PROJECT_BACKUPS"
}

# 初始化系统参数
_init_params() {
    if [ "$OS" != "" ]; then
        return 0
    fi

    if [ -f /etc/os-release ]; then
        OS=$(grep 'PRETTY_NAME' /etc/os-release | awk -F '=' '{print $2}' | tr -d '"')
    elif [ -f /etc/redhat-release ]; then
        OS=$(cat /etc/redhat-release)
    elif [ -f /etc/alpine-release ]; then
        OS="alpine"
    else
        print_message $RED "❌ 不支持的操作系统"
        exit 1
    fi

    # 检测Nginx
    if command -v nginx &> /dev/null; then
        NGINX_VERSION=$(nginx -v 2>&1 | awk -F ': ' '{print $2}' | head -n 1 | head -c 20)
    else
        print_message $RED "❌ 未检测到Nginx，请先安装Nginx"
        exit 1
    fi

    # 查找Nginx配置文件
    if [ -z "$NGINX_CONFIG" ]; then
        # 使用运行中的nginx配置
        NGINX_CONFIG=$(ps -eo pid,cmd | grep nginx | grep master | grep '\-c' | awk -F '-c' '{print $2}' | sed 's/ //g')
    fi

    # 修复NGINX_CONFIG等于nginx.conf的bug
    if [ -z "$NGINX_CONFIG" ] || [ "$NGINX_CONFIG" = "nginx.conf" ]; then
        NGINX_CONFIG=$(nginx -t 2>&1 | grep 'configuration' | head -n 1 | awk -F 'file' '{print $2}' | awk '{print $1}')
    fi

    if [ -z "$NGINX_CONFIG_HOME" ]; then
        NGINX_CONFIG_HOME=$(dirname "$NGINX_CONFIG")
    fi

    # 初始化httpsok参数
    _init_httpsok_params

    print_message $BLUE "操作系统: $OS"
    print_message $BLUE "Nginx版本: $NGINX_VERSION"
    print_message $BLUE "Nginx配置: $NGINX_CONFIG"
    print_message $BLUE "Nginx配置目录: $NGINX_CONFIG_HOME"
    print_message $BLUE "设备UUID: $HTTPSOK_UUID"

    if [ "$NGINX_CONFIG_HOME" = "." ]; then
        print_message $RED "❌ 获取nginx配置文件失败，请手动设置"
        print_message $BLUE "请修改脚本中的以下配置："
        echo "NGINX_CONFIG=/etc/nginx/nginx.conf"
        echo "NGINX_CONFIG_HOME=/etc/nginx"
        exit 1
    fi
}

# 初始化httpsok参数
_init_httpsok_params() {
    if [ "$HTTPSOK_UUID" != "" ]; then
        return 0
    fi

    if [ -f "$PROJECT_UUID_FILE" ]; then
        HTTPSOK_UUID=$(cat "$PROJECT_UUID_FILE")
    fi

    if [ "$HTTPSOK_UUID" != "" ]; then
        return 0
    fi

    _initpath

    if [ -f "/sys/class/dmi/id/product_uuid" ]; then
        HTTPSOK_UUID=$(cat /sys/class/dmi/id/product_uuid)
        if [ "$HTTPSOK_UUID" != "" ]; then
            echo "$HTTPSOK_UUID" > "$PROJECT_UUID_FILE"
            return 0
        fi
    fi

    HTTPSOK_UUID=$(_random_md5)
    echo "$HTTPSOK_UUID" > "$PROJECT_UUID_FILE"
}

# 初始化系统
init_system() {
    print_message $BLUE "正在初始化系统..."

    # 初始化参数
    _init_params

    # 检查Token
    check_token

    print_message $GREEN "✅ 系统初始化完成"
}



# 生成随机MD5
_random_md5() {
    head -c 32 /dev/urandom | md5sum | awk '{print $1}'
}



# 初始化HTTP请求头
_init_http_headers() {
    _H0="Content-Type: text/plain"
    _H1="httpsok-token: $HTTPSOK_TOKEN"
    _H2="httpsok-version: $PROJECT_VERSION"
    _H3="os-name: $OS"
    _H4="nginx-version: $NGINX_VERSION"
    _H5="nginx-config-home: $NGINX_CONFIG_HOME"
    _H6="nginx-config: $NGINX_CONFIG"
    _H7="trace-id: $TRACE_ID"
    _H8="mode: $MODE"
    _H9="httpsok-uuid: $HTTPSOK_UUID"
}

# API GET请求
_api_get() {
    _init_http_headers
    local url="${BASE_API_URL}$1"
    curl -s -H "$_H0" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" -H "$_H6" -H "$_H7" -H "$_H8" -H "$_H9" "$url"
}

# API POST请求
_api_post() {
    _init_http_headers
    local url="${BASE_API_URL}$1"
    local body="$2"
    curl -s -X POST -H "$_H0" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" -H "$_H6" -H "$_H7" -H "$_H8" -H "$_H9" --data-binary "$body" "$url"
}

# API POST文件请求
_api_post_file() {
    _init_http_headers
    local url="${BASE_API_URL}$1"
    local filename="$2"
    
    # 检查文件是否存在
    if [ ! -f "$filename" ]; then
        echo "ERROR: File not found: $filename"
        return 1
    fi
    
    # 执行API请求 - 使用与httpsok.sh相同的格式
    curl -s -X POST -H "$_H0" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" -H "$_H6" -H "$_H7" -H "$_H8" -H "$_H9" --data-binary "@$filename" "$url"
}

# 检查Token有效性
check_token_validity() {
    if [ -z "$HTTPSOK_TOKEN" ]; then
        return 1
    fi
    
    local response=$(_api_get "/status")
    if [ "$response" = "ok" ]; then
        return 0
    else
        return 1
    fi
}

# 检查Token
check_token() {
    if [ -f "$PROJECT_TOKEN_FILE" ]; then
        HTTPSOK_TOKEN=$(cat "$PROJECT_TOKEN_FILE")
        print_message $GREEN "✅ 已加载Token"
        
        # 验证Token有效性
        if check_token_validity; then
            print_message $GREEN "✅ Token验证成功"
        else
            print_message $RED "❌ Token无效，请重新设置"
            HTTPSOK_TOKEN=""
        fi
    else
        print_message $YELLOW "⚠️  未找到Token，请先设置Token"
        HTTPSOK_TOKEN=""
    fi
}

# 设置Token
set_token() {
    print_message $BLUE "请输入您的HTTPSOK Token:"
    read -p "Token: " token

    if [ -n "$token" ]; then
        HTTPSOK_TOKEN="$token"
        
        # 验证Token
        if check_token_validity; then
            echo "$token" > "$PROJECT_TOKEN_FILE"
            print_message $GREEN "✅ Token设置成功并验证通过"
        else
            print_message $RED "❌ Token无效，请检查后重新输入"
            HTTPSOK_TOKEN=""
        fi
    else
        print_message $RED "❌ Token不能为空"
    fi
}

# 证书申请功能
certificate_apply() {
    print_title
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}📝 证书申请${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo

    if [ -z "$HTTPSOK_TOKEN" ]; then
        print_message $RED "❌ 请先设置Token"
        set_token
        return
    fi

    # 输入域名
    echo -e "${WHITE}请输入要申请证书的域名:${NC}"
    read -p "域名: " domain

    if [ -z "$domain" ]; then
        print_message $RED "❌ 域名不能为空"
        return
    fi

    # 选择证书类型
    echo -e "${WHITE}请选择证书类型:${NC}"
    echo -e "  ${WHITE}1.${NC} ${CYAN}单域名证书${NC}"
    echo -e "  ${WHITE}2.${NC} ${CYAN}多域名证书${NC}"
    echo -e "  ${WHITE}3.${NC} ${CYAN}通配符证书${NC}"
    read -p "选择 (1-3): " cert_type

    case $cert_type in
        1) cert_type="single" ;;
        2) cert_type="multi" ;;
        3) cert_type="wildcard" ;;
        *) cert_type="single" ;;
    esac

    # 选择证书提供商
    echo -e "${WHITE}请选择证书提供商:${NC}"
    echo -e "  ${WHITE}1.${NC} ${CYAN}Let's Encrypt (免费)${NC}"
    echo -e "  ${WHITE}2.${NC} ${CYAN}ZeroSSL (免费/付费)${NC}"
    echo -e "  ${WHITE}3.${NC} ${CYAN}Google Trust Services${NC}"
    read -p "选择 (1-3): " provider

    case $provider in
        1) provider="letsencrypt" ;;
        2) provider="zerossl" ;;
        3) provider="google" ;;
        *) provider="letsencrypt" ;;
    esac

    # 申请证书
    print_message $BLUE "正在申请证书..."

    # 这里应该调用API申请证书
    # 由于是演示脚本，这里只是模拟
    print_message $GREEN "✅ 证书申请已提交，请等待DNS验证"
    print_message $YELLOW "请添加以下DNS记录:"
    echo -e "  类型: CNAME"
    echo -e "  主机记录: _acme-challenge"
    echo -e "  记录值: ${domain}.httpsok.com"

    # 等待用户确认DNS配置
    read -p "DNS配置完成后按回车继续..."

    # 验证DNS（使用简化版本，避免长时间等待）
    if verify_dns_simple "$domain"; then
        print_message $BLUE "正在签发证书..."
        sleep 3
        print_message $GREEN "✅ 证书签发成功"
    else
        print_message $YELLOW "⚠️  DNS验证失败，您可以稍后手动运行证书续签"
        print_message $BLUE "或者运行以下命令进行重试："
        echo -e "  ${CYAN}./install/https_panel.sh --run${NC}"
    fi
}

# 限制最大嵌套级别
_include_max_calls=20
_include_global_count=0

# 处理include指令
__process_include() {
    # 递归调用，度数递增
    ((_include_global_count++))

    if [ $_include_global_count -gt $_include_max_calls ]; then
        echo "#######################################################"
        echo "##### warning: Maximum recursion limit reached."
        echo "#######################################################"
        cat /dev/stdin
        return 0
    fi

    tmp=$(cat /dev/stdin | awk -v NGINX_CONFIG=">$NGINX_CONFIG:" -v NGINX_CONFIG_HOME="$NGINX_CONFIG_HOME" '{

        original = $0

        # 移除每行开头和结尾的空白字符
        gsub(/^[[:space:]]+|[[:space:]]+$/, "")
        sub(/^[\t ]*|[\t ]*$/,"")

        # 忽略文件开头的行
        if ($0 ~ /^>/) {
            print original
            next
        }

        # 确定是否以#开头，如果是则忽略
        if ($0 ~ /^#/) {
            print original
            next
        }

        # 确定是否包含include
        if ($0 ~ /^include /) {
            # 忽略mime.types
            if($0 ~ /mime\.types;/){
                print "#import " original
                next
            }

            print "#import " original

            # 替换;
            gsub(/;/, "")

            # 处理相对路径问题
            if (substr($2, 1, 1) != "/") {
                $2 = NGINX_CONFIG_HOME "/" $2
            }

            cmd = "ls -1 " $2 " 2>/dev/null | xargs -I {} awk '\'' BEGIN {print \"#included-begin {};\" } {print}  END{ print \"#included-end {};\"  } '\'' {} "

            system(cmd)
            print ""

            next
        }

        print original

    }')

    if echo "$tmp" | grep -v '#' | grep -q "include"; then
        # 执行递归调用
        echo "$tmp" | __process_include
    else
        # 结束递归调用
        echo "$tmp"
    fi
}

# 解析Nginx配置获取证书信息
_parse_nginx_config() {
    _init_params

    # 检查配置文件是否存在
    if [ ! -f "$NGINX_CONFIG" ]; then
        print_message $RED "❌ Nginx配置文件不存在: $NGINX_CONFIG"
        return 1
    fi

    print_message $BLUE "正在解析Nginx配置: $NGINX_CONFIG"

    # 处理配置文件中的include指令
    config_text=$(cat $NGINX_CONFIG | __process_include)
    tmp_name="/tmp/nginx_config_$$.tmp"
    echo "$config_text" > $tmp_name
    
    # 检查临时文件是否创建成功
    if [ ! -f "$tmp_name" ]; then
        print_message $RED "❌ 临时文件创建失败"
        return 1
    fi
    
    print_message $BLUE "正在调用API解析配置..."
    
    # 调用API解析配置
    print_message $BLUE "正在发送配置到API服务器..."
    preparse=$(_api_post_file "/preparse" "$tmp_name")
    
    # 清理临时文件
    rm -rf "$tmp_name" > /dev/null 2>&1
    
    # 检查API响应
    if [ -z "$preparse" ]; then
        print_message $RED "❌ 配置解析失败 - API返回空响应"
        print_message $BLUE "请检查："
        print_message $BLUE "1. 网络连接是否正常"
        print_message $BLUE "2. Token是否有效"
        print_message $BLUE "3. API服务是否可用"
        
        # 测试API连接
        print_message $BLUE "正在测试API连接..."
        local api_test=$(_api_get "/status")
        if [ "$api_test" = "ok" ]; then
            print_message $GREEN "✅ API连接正常"
        else
            print_message $RED "❌ API连接失败: $api_test"
        fi
        
        return 1
    fi
    
    # 检查是否包含错误信息
    if echo "$preparse" | grep -q "error\|Error\|ERROR"; then
        print_message $RED "❌ 配置解析失败 - API返回错误"
        print_message $RED "错误信息: $preparse"
        return 1
    fi
    
    print_message $GREEN "✅ 配置解析成功"
    return 0
}

# 检查DNS配置
_check_dns() {
    local codes=$(echo "$preparse" | awk -F ',' '{print $1}' | tr '\n' ',' )
    local url="/checkDns"
    local resp=$(_api_get "$url")
    local status=$(echo "$resp" | head -n 1)
    
    case $status in
        "3")
            print_message $GREEN "✅ DNS检查通过"
            ;;
        "13")
            print_message $RED "❌ 代码无效"
            ;;
        *)
            print_message $RED "❌ DNS检查失败: $resp"
            ;;
    esac
}

# 验证DNS配置（带重试机制）
verify_dns() {
    local domain="$1"
    local max_retries=10
    local retry_interval=30
    
    print_message $BLUE "正在验证DNS配置..."
    print_message $YELLOW "DNS记录生效需要时间，请耐心等待..."

    for ((i=1; i<=max_retries; i++)); do
        print_message $BLUE "第 $i 次验证DNS配置..."
        
        # 检查DNS解析
        local challenge_domain="_acme-challenge.$domain"
        local resolved=$(dig +short "$challenge_domain" CNAME 2>/dev/null)
        
        print_message $BLUE "DNS解析结果: $resolved"
        
        if echo "$resolved" | grep -q "httpsok.com"; then
            print_message $GREEN "✅ DNS验证成功"
            print_message $BLUE "正在签发证书..."
            sleep 3
            print_message $GREEN "✅ 证书签发成功"
            return 0
        else
            if [ $i -lt $max_retries ]; then
                print_message $YELLOW "⚠️  DNS验证失败，等待 ${retry_interval} 秒后重试..."
                print_message $BLUE "请确保已添加以下DNS记录："
                echo -e "  类型: ${YELLOW}CNAME${NC}"
                echo -e "  主机记录: ${YELLOW}_acme-challenge${NC}"
                echo -e "  记录值: ${YELLOW}${domain}.httpsok.com${NC}"
                echo -e "  TTL: ${YELLOW}300${NC}"
                sleep $retry_interval
            else
                print_message $RED "❌ DNS验证失败，已达到最大重试次数"
                print_message $YELLOW "请检查DNS记录是否正确配置，然后手动运行证书续签"
                return 1
            fi
        fi
    done
}

# 验证DNS配置（简化版本，用于证书申请）
verify_dns_simple() {
    local domain="$1"
    print_message $BLUE "正在验证DNS配置..."

    # 检查DNS解析
    local challenge_domain="_acme-challenge.$domain"
    local resolved=$(dig +short "$challenge_domain" CNAME 2>/dev/null)

    if echo "$resolved" | grep -q "httpsok.com"; then
        print_message $GREEN "✅ DNS验证成功"
        return 0
    else
        print_message $RED "❌ DNS验证失败，请检查DNS配置"
        print_message $BLUE "请确保已添加以下DNS记录："
        echo -e "  类型: ${YELLOW}CNAME${NC}"
        echo -e "  主机记录: ${YELLOW}_acme-challenge${NC}"
        echo -e "  记录值: ${YELLOW}${domain}.httpsok.com${NC}"
        echo -e "  TTL: ${YELLOW}300${NC}"
        return 1
    fi
}

# 检查证书状态
_check_cert_status() {
    local code="$1"
    local cert_file="$2"
    local cert_key_file="$3"
    local depth="$4"
    
    if [ $depth -le 0 ]; then
        print_message $RED "❌ 检查次数超限"
        return 1
    fi
    
    local url="/check?code=$code"
    local resp=$(_api_get "$url")
    local status=$(echo "$resp" | head -n 1)
    
    case $status in
        "1")
            # 证书更新成功
            local md5_line=$(echo "$resp" | awk 'NR==2')
            local cert_file_md5=$(echo $md5_line | awk -F ',' '{print $1}')
            local cert_key_file_md5=$(echo $md5_line | awk -F ',' '{print $2}')
            
            local tmp_cert_file="/tmp/$code.cer"
            local tmp_cert_key_file="/tmp/$code.key"
            
            # 下载新证书
            _api_get "/cert/$code.cer" > "$tmp_cert_file" && _api_get "/cert/$code.key" > "$tmp_cert_key_file"
            
            # MD5校验
            local tmp_cert_md5=$(md5sum "$tmp_cert_file" | awk '{print $1}')
            local tmp_cert_key_md5=$(md5sum "$tmp_cert_key_file" | awk '{print $1}')
            
            if [ "$cert_file_md5" = "$tmp_cert_md5" ] && [ "$cert_key_file_md5" = "$tmp_cert_key_md5" ]; then
                # 创建证书文件
                _create_cert_file "$code" "$cert_file"
                _create_cert_file "$code" "$cert_key_file"
                mv "$tmp_cert_file" "$cert_file"
                mv "$tmp_cert_key_file" "$cert_key_file"
                print_message $GREEN "✅ 证书更新成功: $code"
                echo "latest_code $code"
            else
                print_message $RED "❌ 证书更新失败: MD5校验失败"
            fi
            ;;
        "2")
            print_message $YELLOW "⏳ 正在处理中，请稍等..."
            sleep 10
            _check_cert_status "$code" "$cert_file" "$cert_key_file" $((depth - 1))
            ;;
        "3")
            print_message $GREEN "✅ 证书有效: $code"
            ;;
        "12")
            print_message $RED "❌ DNS CNAME验证失败"
            ;;
        "13")
            print_message $RED "❌ 非法请求"
            ;;
        *)
            print_message $RED "❌ 检查失败: $resp"
            ;;
    esac
}

# 创建证书文件
_create_cert_file() {
    local code="$1"
    local file_path="$2"
    
    if [ ! -e "$file_path" ]; then
        local dir_path=$(dirname "$file_path")
        mkdir -p "$dir_path"
        touch "$file_path"
        print_message $GREEN "✅ 创建文件: $file_path"
    else
        # 备份现有文件
        if [ -f "$file_path" ]; then
            local filename=$(basename "$file_path")
            local date=$(date +"%Y%m%d%H%M%S")
            local backup_file_path="$PROJECT_BACKUPS/$filename.$date"
            
            if [ ! -f "$backup_file_path" ]; then
                mv "$file_path" "$backup_file_path"
                print_message $GREEN "✅ 备份文件: $file_path -> $backup_file_path"
            fi
        fi
    fi
}

# 重载Nginx
_reload_nginx() {
    if [ -z "$latest_code" ]; then
        print_message $BLUE "无需重载Nginx"
        return 0
    fi

    print_message $BLUE "正在重载Nginx..."
    
    # 切换到Nginx配置目录
    cd "$NGINX_CONFIG_HOME"
    
    # 测试配置
    local test_msg=$($NGINX_BIN -t 2>&1)
    if [ $? != 0 ]; then
        print_message $RED "❌ Nginx配置测试失败"
        print_message $RED "$test_msg"
        return 1
    fi
    
    # 重载Nginx
    local reload_msg=$($NGINX_BIN -s reload 2>&1)
    if [ $? -eq 0 ]; then
        print_message $GREEN "✅ Nginx重载成功"
    else
        # 检查Nginx是否运行
        local pid=$(ps -e | grep nginx | grep -v 'grep' | head -n 1 | awk '{print $1}')
        if [ -z "$pid" ]; then
            print_message $YELLOW "⚠️  Nginx服务未启动，请手动启动服务"
        fi
        print_message $RED "❌ Nginx重载失败"
        print_message $RED "$reload_msg"
        return 1
    fi
}

# 证书续签功能
certificate_renew() {
    print_title
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔄 证书续签${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo

    if [ -z "$HTTPSOK_TOKEN" ]; then
        print_message $RED "❌ 请先设置Token"
        return
    fi

    print_message $BLUE "正在检查证书状态..."

    # 初始化参数
    _init_params
    
    # 解析Nginx配置获取证书列表
    if ! _parse_nginx_config; then
        print_message $RED "❌ 无法解析Nginx配置"
        return
    fi
    
    # 显示证书列表
    echo -e "${WHITE}当前证书列表:${NC}"
    local cert_index=1
    local cert_codes=()
    local cert_files=()
    local cert_key_files=()
    
    while IFS=',' read -r code cert_file cert_key_file; do
        if [ -n "$code" ] && [ -n "$cert_file" ] && [ -n "$cert_key_file" ]; then
            local domain=$(basename "$cert_file" .crt | sed 's/\.crt$//')
            if [ -z "$domain" ]; then
                domain=$(basename "$cert_file" .pem | sed 's/\.pem$//')
            fi
            
            echo -e "  ${WHITE}$cert_index.${NC} ${CYAN}$domain${NC} (代码: $code)"
            cert_codes+=("$code")
            cert_files+=("$cert_file")
            cert_key_files+=("$cert_key_file")
            cert_index=$((cert_index + 1))
        fi
    done <<< "$preparse"
    
    if [ ${#cert_codes[@]} -eq 0 ]; then
        print_message $YELLOW "⚠️  未找到可续签的证书"
        return
    fi
    
    echo
    read -p "请选择要续签的证书 (1-${#cert_codes[@]}): " cert_choice
    
    if [ "$cert_choice" -lt 1 ] || [ "$cert_choice" -gt ${#cert_codes[@]} ]; then
        print_message $RED "❌ 无效选择"
        return
    fi
    
    local selected_index=$((cert_choice - 1))
    local selected_code="${cert_codes[$selected_index]}"
    local selected_cert_file="${cert_files[$selected_index]}"
    local selected_cert_key_file="${cert_key_files[$selected_index]}"
    
    print_message $BLUE "正在续签证书: $selected_code"
    
    # 检查证书状态
    _check_cert_status "$selected_code" "$selected_cert_file" "$selected_cert_key_file" 60
    
    # 重载Nginx
    if [ -n "$latest_code" ]; then
        _reload_nginx
    fi
}

# 证书管理功能
certificate_manage() {
    print_title
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}📋 证书管理${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo

    echo -e "${WHITE}证书管理选项:${NC}"
    echo -e "  ${WHITE}1.${NC} ${CYAN}查看证书列表${NC}"
    echo -e "  ${WHITE}2.${NC} ${CYAN}查看证书详情${NC}"
    echo -e "  ${WHITE}3.${NC} ${CYAN}删除证书${NC}"
    echo -e "  ${WHITE}4.${NC} ${CYAN}证书备份${NC}"
    echo -e "  ${WHITE}5.${NC} ${CYAN}证书恢复${NC}"
    echo

    read -p "请选择操作 (1-5): " manage_choice

    case $manage_choice in
        1) show_certificate_list ;;
        2) show_certificate_detail ;;
        3) delete_certificate ;;
        4) backup_certificate ;;
        5) restore_certificate ;;
        *) print_message $RED "❌ 无效选择" ;;
    esac
}

# 证书下载功能
certificate_download() {
    print_title
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}📥 证书下载${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo

    if [ -z "$HTTPSOK_TOKEN" ]; then
        print_message $RED "❌ 请先设置Token"
        set_token
        return
    fi

    # 初始化参数
    _init_params
    
    # 解析Nginx配置获取证书信息
    if ! _parse_nginx_config; then
        print_message $RED "❌ 无法解析Nginx配置"
        return
    fi

    echo -e "${WHITE}可下载的证书列表:${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    printf "%-20s %-30s %-30s\n" "证书代码" "证书文件" "私钥文件"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    local cert_count=0
    while IFS=',' read -r code cert_file cert_key_file; do
        if [ -n "$code" ] && [ -n "$cert_file" ] && [ -n "$cert_key_file" ]; then
            cert_count=$((cert_count + 1))
            printf "%-20s %-30s %-30s\n" "$code" "$cert_file" "$cert_key_file"
        fi
    done <<< "$preparse"
    
    if [ $cert_count -eq 0 ]; then
        print_message $YELLOW "⚠️  未找到可下载的证书"
        return
    fi

    echo
    echo -e "${WHITE}请选择要下载的证书:${NC}"
    read -p "证书代码: " download_code

    if [ -z "$download_code" ]; then
        print_message $RED "❌ 证书代码不能为空"
        return
    fi

    # 验证证书代码是否存在
    local found=0
    while IFS=',' read -r code cert_file cert_key_file; do
        if [ "$code" = "$download_code" ]; then
            found=1
            break
        fi
    done <<< "$preparse"

    if [ $found -eq 0 ]; then
        print_message $RED "❌ 证书代码不存在: $download_code"
        return
    fi

    # 选择下载目录
    echo -e "${WHITE}请选择下载目录:${NC}"
    read -p "下载目录 (默认: $HOME/certs): " download_dir
    download_dir=${download_dir:-"$HOME/certs"}

    # 创建下载目录
    if [ ! -d "$download_dir" ]; then
        mkdir -p "$download_dir"
        print_message $GREEN "✅ 创建下载目录: $download_dir"
    fi

    # 下载证书文件
    print_message $BLUE "正在下载证书文件..."
    
    local cert_filename=$(basename "$cert_file")
    local key_filename=$(basename "$cert_key_file")
    local local_cert_file="$download_dir/$cert_filename"
    local local_key_file="$download_dir/$key_filename"

    # 下载证书
    if _api_get "/cert/$download_code.cer" > "$local_cert_file"; then
        print_message $GREEN "✅ 证书文件下载成功: $local_cert_file"
    else
        print_message $RED "❌ 证书文件下载失败"
        return
    fi

    # 下载私钥
    if _api_get "/cert/$download_code.key" > "$local_key_file"; then
        print_message $GREEN "✅ 私钥文件下载成功: $local_key_file"
    else
        print_message $RED "❌ 私钥文件下载失败"
        rm -f "$local_cert_file"
        return
    fi

    # 设置文件权限
    chmod 644 "$local_cert_file"
    chmod 600 "$local_key_file"
    print_message $GREEN "✅ 文件权限设置完成"

    print_message $GREEN "✅ 证书下载完成！"
    echo -e "${WHITE}证书文件:${NC} $local_cert_file"
    echo -e "${WHITE}私钥文件:${NC} $local_key_file"
}

# 证书部署功能
certificate_deploy() {
    print_title
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🚀 证书部署${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo

    if [ -z "$HTTPSOK_TOKEN" ]; then
        print_message $RED "❌ 请先设置Token"
        set_token
        return
    fi

    # 初始化参数
    _init_params
    
    # 解析Nginx配置获取证书信息
    if ! _parse_nginx_config; then
        print_message $RED "❌ 无法解析Nginx配置"
        return
    fi

    echo -e "${WHITE}可部署的证书列表:${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    printf "%-20s %-30s %-30s\n" "证书代码" "证书文件" "私钥文件"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    local cert_count=0
    while IFS=',' read -r code cert_file cert_key_file; do
        if [ -n "$code" ] && [ -n "$cert_file" ] && [ -n "$cert_key_file" ]; then
            cert_count=$((cert_count + 1))
            printf "%-20s %-30s %-30s\n" "$code" "$cert_file" "$cert_key_file"
        fi
    done <<< "$preparse"
    
    if [ $cert_count -eq 0 ]; then
        print_message $YELLOW "⚠️  未找到可部署的证书"
        return
    fi

    echo
    echo -e "${WHITE}请选择要部署的证书:${NC}"
    read -p "证书代码: " deploy_code

    if [ -z "$deploy_code" ]; then
        print_message $RED "❌ 证书代码不能为空"
        return
    fi

    # 验证证书代码是否存在
    local found=0
    local target_cert_file=""
    local target_key_file=""
    while IFS=',' read -r code cert_file cert_key_file; do
        if [ "$code" = "$deploy_code" ]; then
            found=1
            target_cert_file="$cert_file"
            target_key_file="$cert_key_file"
            break
        fi
    done <<< "$preparse"

    if [ $found -eq 0 ]; then
        print_message $RED "❌ 证书代码不存在: $deploy_code"
        return
    fi

    print_message $BLUE "正在部署证书: $deploy_code"
    print_message $BLUE "证书文件: $target_cert_file"
    print_message $BLUE "私钥文件: $target_key_file"

    # 检查证书状态
    local url="/check?code=$deploy_code"
    local resp=$(_api_get "$url")
    local status=$(echo "$resp" | head -n 1)

    case $status in
        "1")
            # 证书需要更新
            print_message $BLUE "检测到新证书，正在更新..."
            
            local md5_line=$(echo "$resp" | awk 'NR==2')
            local cert_file_md5=$(echo $md5_line | awk -F ',' '{print $1}')
            local cert_key_file_md5=$(echo $md5_line | awk -F ',' '{print $2}')
            
            local tmp_cert_file="/tmp/$deploy_code.cer"
            local tmp_cert_key_file="/tmp/$deploy_code.key"
            
            # 下载新证书
            if _api_get "/cert/$deploy_code.cer" > "$tmp_cert_file" && _api_get "/cert/$deploy_code.key" > "$tmp_cert_key_file"; then
                # MD5校验
                local tmp_cert_md5=$(md5sum "$tmp_cert_file" | awk '{print $1}')
                local tmp_cert_key_md5=$(md5sum "$tmp_cert_key_file" | awk '{print $1}')
                
                if [ "$cert_file_md5" = "$tmp_cert_md5" ] && [ "$cert_key_file_md5" = "$tmp_cert_key_md5" ]; then
                    # 创建证书文件
                    _create_cert_file "$deploy_code" "$target_cert_file"
                    _create_cert_file "$deploy_code" "$target_key_file"
                    mv "$tmp_cert_file" "$target_cert_file"
                    mv "$tmp_cert_key_file" "$target_key_file"
                    print_message $GREEN "✅ 证书更新成功: $deploy_code"
                    
                    # 重载Nginx
                    _reload_nginx
                else
                    print_message $RED "❌ 证书更新失败: MD5校验失败"
                    rm -f "$tmp_cert_file" "$tmp_cert_key_file"
                fi
            else
                print_message $RED "❌ 证书下载失败"
            fi
            ;;
        "2")
            print_message $YELLOW "⏳ 证书正在处理中，请稍等..."
            ;;
        "3")
            print_message $GREEN "✅ 证书已是最新版本"
            
            # 检查是否需要重载Nginx
            echo -e "${WHITE}是否重载Nginx配置? (y/N):${NC}"
            read -p "" reload_choice
            if [[ "$reload_choice" =~ ^[Yy]$ ]]; then
                _reload_nginx
            fi
            ;;
        "12")
            print_message $RED "❌ DNS CNAME验证失败"
            ;;
        "13")
            print_message $RED "❌ 非法请求"
            ;;
        *)
            print_message $RED "❌ 部署失败: $resp"
            ;;
    esac
}

# 显示证书列表
show_certificate_list() {
    print_message $BLUE "正在获取证书列表..."
    
    # 检查Token
    if [ -z "$HTTPSOK_TOKEN" ]; then
        print_message $RED "❌ 请先设置Token"
        return
    fi
    
    # 初始化参数
    _init_params
    
    # 解析Nginx配置
    if ! _parse_nginx_config; then
        print_message $RED "❌ 无法解析Nginx配置"
        return
    fi

    echo -e "${WHITE}证书列表:${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    printf "%-20s %-12s %-15s %-12s\n" "域名" "类型" "状态" "有效期"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 解析证书信息
    local cert_count=0
    while IFS=',' read -r code cert_file cert_key_file; do
        if [ -n "$code" ] && [ -n "$cert_file" ] && [ -n "$cert_key_file" ]; then
            cert_count=$((cert_count + 1))
            
            # 从证书文件路径提取域名
            local domain=$(basename "$cert_file" .crt | sed 's/\.crt$//')
            if [ -z "$domain" ]; then
                domain=$(basename "$cert_file" .pem | sed 's/\.pem$//')
            fi
            
            # 检查证书状态
            local status="正常"
            local expire_date="未知"
            
            if [ -f "$cert_file" ]; then
                # 检查证书过期时间
                local expire_info=$(openssl x509 -in "$cert_file" -noout -dates 2>/dev/null | grep "notAfter")
                if [ -n "$expire_info" ]; then
                    expire_date=$(echo "$expire_info" | cut -d'=' -f2 | date -f - +%Y-%m-%d 2>/dev/null || echo "未知")
                    
                    # 检查是否即将过期（30天内）
                    local expire_timestamp=$(date -d "$expire_date" +%s 2>/dev/null)
                    local current_timestamp=$(date +%s)
                    local days_left=$(( (expire_timestamp - current_timestamp) / 86400 ))
                    
                    if [ $days_left -lt 0 ]; then
                        status="已过期"
                    elif [ $days_left -lt 30 ]; then
                        status="即将过期"
                    fi
                fi
            else
                status="文件缺失"
            fi
            
            # 判断证书类型
            local cert_type="单域名"
            if [[ "$domain" == *"*"* ]]; then
                cert_type="通配符"
            fi
            
            printf "%-20s %-12s %-15s %-12s\n" "$domain" "$cert_type" "$status" "$expire_date"
        fi
    done <<< "$preparse"
    
    if [ $cert_count -eq 0 ]; then
        echo -e "${YELLOW}未找到SSL证书配置${NC}"
    fi
    
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    print_message $GREEN "✅ 共找到 $cert_count 个证书"
}

# 显示证书详情
show_certificate_detail() {
    # 检查Token
    if [ -z "$HTTPSOK_TOKEN" ]; then
        print_message $RED "❌ 请先设置Token"
        return
    fi
    
    # 初始化参数
    _init_params
    
    # 解析Nginx配置获取证书列表
    if ! _parse_nginx_config; then
        print_message $RED "❌ 无法解析Nginx配置"
        return
    fi
    
    # 显示证书列表供选择
    echo -e "${WHITE}可查看的证书列表:${NC}"
    local cert_index=1
    local cert_codes=()
    local cert_files=()
    local cert_key_files=()
    
    while IFS=',' read -r code cert_file cert_key_file; do
        if [ -n "$code" ] && [ -n "$cert_file" ] && [ -n "$cert_key_file" ]; then
            local domain=$(basename "$cert_file" .crt | sed 's/\.crt$//')
            if [ -z "$domain" ]; then
                domain=$(basename "$cert_file" .pem | sed 's/\.pem$//')
            fi
            
            echo -e "  ${WHITE}$cert_index.${NC} ${CYAN}$domain${NC} (代码: $code)"
            cert_codes+=("$code")
            cert_files+=("$cert_file")
            cert_key_files+=("$cert_key_file")
            cert_index=$((cert_index + 1))
        fi
    done <<< "$preparse"
    
    if [ ${#cert_codes[@]} -eq 0 ]; then
        print_message $YELLOW "⚠️  未找到可查看的证书"
        return
    fi
    
    echo
    read -p "请选择要查看的证书 (1-${#cert_codes[@]}): " cert_choice
    
    if [ "$cert_choice" -lt 1 ] || [ "$cert_choice" -gt ${#cert_codes[@]} ]; then
        print_message $RED "❌ 无效选择"
        return
    fi
    
    local selected_index=$((cert_choice - 1))
    local selected_code="${cert_codes[$selected_index]}"
    local selected_cert_file="${cert_files[$selected_index]}"
    local selected_cert_key_file="${cert_key_files[$selected_index]}"
    local selected_domain=$(basename "$selected_cert_file" .crt | sed 's/\.crt$//')
    if [ -z "$selected_domain" ]; then
        selected_domain=$(basename "$selected_cert_file" .pem | sed 's/\.pem$//')
    fi
    
    echo -e "${WHITE}证书详情 - ${CYAN}$selected_domain${NC}:${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "域名: ${CYAN}$selected_domain${NC}"
    echo -e "证书代码: ${CYAN}$selected_code${NC}"
    echo -e "证书文件: ${CYAN}$selected_cert_file${NC}"
    echo -e "私钥文件: ${CYAN}$selected_cert_key_file${NC}"
    
    # 检查证书文件是否存在
    if [ -f "$selected_cert_file" ]; then
        # 获取证书详细信息
        local cert_info=$(openssl x509 -in "$selected_cert_file" -noout -text 2>/dev/null)
        if [ -n "$cert_info" ]; then
            # 提取证书类型
            local cert_type="单域名证书"
            if echo "$cert_info" | grep -q "DNS:"; then
                local dns_count=$(echo "$cert_info" | grep -c "DNS:")
                if [ $dns_count -gt 1 ]; then
                    cert_type="多域名证书"
                fi
            fi
            if echo "$cert_info" | grep -q "\\*\\."; then
                cert_type="通配符证书"
            fi
            
            # 提取签发时间
            local not_before=$(openssl x509 -in "$selected_cert_file" -noout -startdate 2>/dev/null | cut -d'=' -f2)
            local not_after=$(openssl x509 -in "$selected_cert_file" -noout -enddate 2>/dev/null | cut -d'=' -f2)
            
            # 计算剩余天数
            local expire_timestamp=$(date -d "$not_after" +%s 2>/dev/null)
            local current_timestamp=$(date +%s)
            local days_left=$(( (expire_timestamp - current_timestamp) / 86400 ))
            
            # 判断状态
            local status="正常"
            local status_color=$GREEN
            if [ $days_left -lt 0 ]; then
                status="已过期"
                status_color=$RED
            elif [ $days_left -lt 30 ]; then
                status="即将过期"
                status_color=$YELLOW
            fi
            
            echo -e "证书类型: ${CYAN}$cert_type${NC}"
            echo -e "状态: ${status_color}$status${NC}"
            echo -e "签发时间: ${CYAN}$not_before${NC}"
            echo -e "过期时间: ${CYAN}$not_after${NC}"
            echo -e "剩余天数: ${CYAN}$days_left 天${NC}"
            
            # 检查证书有效性
            if openssl x509 -in "$selected_cert_file" -checkend 0 >/dev/null 2>&1; then
                echo -e "证书有效性: ${GREEN}有效${NC}"
            else
                echo -e "证书有效性: ${RED}无效${NC}"
            fi
        else
            echo -e "证书类型: ${CYAN}未知${NC}"
            echo -e "状态: ${YELLOW}无法读取证书信息${NC}"
        fi
    else
        echo -e "证书类型: ${CYAN}未知${NC}"
        echo -e "状态: ${RED}证书文件不存在${NC}"
    fi
    
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}

# 删除证书
delete_certificate() {
    # 检查Token
    if [ -z "$HTTPSOK_TOKEN" ]; then
        print_message $RED "❌ 请先设置Token"
        return
    fi
    
    # 初始化参数
    _init_params
    
    # 解析Nginx配置获取证书列表
    if ! _parse_nginx_config; then
        print_message $RED "❌ 无法解析Nginx配置"
        return
    fi
    
    # 显示证书列表供选择
    echo -e "${WHITE}可删除的证书列表:${NC}"
    local cert_index=1
    local cert_codes=()
    local cert_files=()
    local cert_key_files=()
    
    while IFS=',' read -r code cert_file cert_key_file; do
        if [ -n "$code" ] && [ -n "$cert_file" ] && [ -n "$cert_key_file" ]; then
            local domain=$(basename "$cert_file" .crt | sed 's/\.crt$//')
            if [ -z "$domain" ]; then
                domain=$(basename "$cert_file" .pem | sed 's/\.pem$//')
            fi
            
            echo -e "  ${WHITE}$cert_index.${NC} ${CYAN}$domain${NC} (代码: $code)"
            cert_codes+=("$code")
            cert_files+=("$cert_file")
            cert_key_files+=("$cert_key_file")
            cert_index=$((cert_index + 1))
        fi
    done <<< "$preparse"
    
    if [ ${#cert_codes[@]} -eq 0 ]; then
        print_message $YELLOW "⚠️  未找到可删除的证书"
        return
    fi
    
    echo
    read -p "请选择要删除的证书 (1-${#cert_codes[@]}): " cert_choice
    
    if [ "$cert_choice" -lt 1 ] || [ "$cert_choice" -gt ${#cert_codes[@]} ]; then
        print_message $RED "❌ 无效选择"
        return
    fi
    
    local selected_index=$((cert_choice - 1))
    local selected_code="${cert_codes[$selected_index]}"
    local selected_cert_file="${cert_files[$selected_index]}"
    local selected_cert_key_file="${cert_key_files[$selected_index]}"
    local selected_domain=$(basename "$selected_cert_file" .crt | sed 's/\.crt$//')
    if [ -z "$selected_domain" ]; then
        selected_domain=$(basename "$selected_cert_file" .pem | sed 's/\.pem$//')
    fi
    
    echo -e "${YELLOW}⚠️  确定要删除证书 ${CYAN}$selected_domain${YELLOW} 吗？${NC}"
    echo -e "证书代码: ${CYAN}$selected_code${NC}"
    echo -e "证书文件: ${CYAN}$selected_cert_file${NC}"
    echo -e "私钥文件: ${CYAN}$selected_cert_key_file${NC}"
    read -p "确认删除? (y/n): " confirm
    
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        print_message $BLUE "正在删除证书: $selected_domain"
        
        # 备份证书文件
        if [ -f "$selected_cert_file" ]; then
            local backup_cert="$PROJECT_BACKUPS/$(basename "$selected_cert_file").$(date +%Y%m%d_%H%M%S)"
            cp "$selected_cert_file" "$backup_cert"
            print_message $GREEN "✅ 证书文件已备份: $backup_cert"
        fi
        
        if [ -f "$selected_cert_key_file" ]; then
            local backup_key="$PROJECT_BACKUPS/$(basename "$selected_cert_key_file").$(date +%Y%m%d_%H%M%S)"
            cp "$selected_cert_key_file" "$backup_key"
            print_message $GREEN "✅ 私钥文件已备份: $backup_key"
        fi
        
        # 删除证书文件
        rm -f "$selected_cert_file" "$selected_cert_key_file"
        print_message $GREEN "✅ 证书删除成功"
        
        # 重载Nginx
        print_message $BLUE "正在重载Nginx..."
        _reload_nginx
    else
        print_message $BLUE "取消删除操作"
    fi
}

# 证书备份
backup_certificate() {
    # 检查Token
    if [ -z "$HTTPSOK_TOKEN" ]; then
        print_message $RED "❌ 请先设置Token"
        return
    fi
    
    # 初始化参数
    _init_params
    
    # 解析Nginx配置获取证书列表
    if ! _parse_nginx_config; then
        print_message $RED "❌ 无法解析Nginx配置"
        return
    fi
    
    # 显示证书列表供选择
    echo -e "${WHITE}可备份的证书列表:${NC}"
    local cert_index=1
    local cert_codes=()
    local cert_files=()
    local cert_key_files=()
    
    while IFS=',' read -r code cert_file cert_key_file; do
        if [ -n "$code" ] && [ -n "$cert_file" ] && [ -n "$cert_key_file" ]; then
            local domain=$(basename "$cert_file" .crt | sed 's/\.crt$//')
            if [ -z "$domain" ]; then
                domain=$(basename "$cert_file" .pem | sed 's/\.pem$//')
            fi
            
            echo -e "  ${WHITE}$cert_index.${NC} ${CYAN}$domain${NC} (代码: $code)"
            cert_codes+=("$code")
            cert_files+=("$cert_file")
            cert_key_files+=("$cert_key_file")
            cert_index=$((cert_index + 1))
        fi
    done <<< "$preparse"
    
    if [ ${#cert_codes[@]} -eq 0 ]; then
        print_message $YELLOW "⚠️  未找到可备份的证书"
        return
    fi
    
    echo
    read -p "请选择要备份的证书 (1-${#cert_codes[@]}): " cert_choice
    
    if [ "$cert_choice" -lt 1 ] || [ "$cert_choice" -gt ${#cert_codes[@]} ]; then
        print_message $RED "❌ 无效选择"
        return
    fi
    
    local selected_index=$((cert_choice - 1))
    local selected_code="${cert_codes[$selected_index]}"
    local selected_cert_file="${cert_files[$selected_index]}"
    local selected_cert_key_file="${cert_key_files[$selected_index]}"
    local selected_domain=$(basename "$selected_cert_file" .crt | sed 's/\.crt$//')
    if [ -z "$selected_domain" ]; then
        selected_domain=$(basename "$selected_cert_file" .pem | sed 's/\.pem$//')
    fi
    
    print_message $BLUE "正在备份证书: $selected_domain"
    
    # 创建备份目录
    local backup_dir="$PROJECT_BACKUPS/$selected_domain"
    mkdir -p "$backup_dir"
    
    # 备份证书文件
    local backup_files=()
    if [ -f "$selected_cert_file" ]; then
        local backup_cert="$backup_dir/$(basename "$selected_cert_file").$(date +%Y%m%d_%H%M%S)"
        cp "$selected_cert_file" "$backup_cert"
        backup_files+=("$backup_cert")
        print_message $GREEN "✅ 证书文件已备份: $backup_cert"
    fi
    
    if [ -f "$selected_cert_key_file" ]; then
        local backup_key="$backup_dir/$(basename "$selected_cert_key_file").$(date +%Y%m%d_%H%M%S)"
        cp "$selected_cert_key_file" "$backup_key"
        backup_files+=("$backup_key")
        print_message $GREEN "✅ 私钥文件已备份: $backup_key"
    fi
    
    # 创建压缩包
    if [ ${#backup_files[@]} -gt 0 ]; then
        local backup_archive="$PROJECT_BACKUPS/${selected_domain}_$(date +%Y%m%d_%H%M%S).tar.gz"
        cd "$backup_dir" && tar -czf "$backup_archive" * && cd - > /dev/null
        print_message $GREEN "✅ 证书备份成功"
        echo -e "备份位置: ${CYAN}$backup_archive${NC}"
        
        # 清理临时文件
        rm -rf "$backup_dir"
    else
        print_message $YELLOW "⚠️  没有找到可备份的证书文件"
    fi
}

# 证书恢复
restore_certificate() {
    echo -e "${WHITE}可用的备份文件:${NC}"
    echo -e "  ${WHITE}1.${NC} ${CYAN}example.com_20250101_120000.tar.gz${NC}"
    echo -e "  ${WHITE}2.${NC} ${CYAN}test.com_20250101_110000.tar.gz${NC}"
    read -p "选择要恢复的备份 (1-2): " backup_choice
    
    case $backup_choice in
        1) backup_file="example.com_20250101_120000.tar.gz" ;;
        2) backup_file="test.com_20250101_110000.tar.gz" ;;
        *) print_message $RED "❌ 无效选择"; return ;;
    esac
    
    print_message $BLUE "正在恢复证书: $backup_file"
    sleep 2
    print_message $GREEN "✅ 证书恢复成功"
}

# 证书监控功能
certificate_monitor() {
    print_title
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}📊 证书监控${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo
    
    if [ -z "$HTTPSOK_TOKEN" ]; then
        print_message $RED "❌ 请先设置Token"
        return
    fi
    
    print_message $BLUE "正在检查证书状态..."
    
    # 初始化参数
    _init_params
    
    # 解析Nginx配置获取证书列表
    if ! _parse_nginx_config; then
        print_message $RED "❌ 无法解析Nginx配置"
        return
    fi
    
    # 统计证书状态
    local total_certs=0
    local normal_certs=0
    local expiring_certs=0
    local expired_certs=0
    local missing_certs=0
    
    echo -e "${WHITE}详细状态:${NC}"
    
    while IFS=',' read -r code cert_file cert_key_file; do
        if [ -n "$code" ] && [ -n "$cert_file" ] && [ -n "$cert_key_file" ]; then
            total_certs=$((total_certs + 1))
            
            # 从证书文件路径提取域名
            local domain=$(basename "$cert_file" .crt | sed 's/\.crt$//')
            if [ -z "$domain" ]; then
                domain=$(basename "$cert_file" .pem | sed 's/\.pem$//')
            fi
            
            if [ -f "$cert_file" ]; then
                # 检查证书过期时间
                local expire_info=$(openssl x509 -in "$cert_file" -noout -dates 2>/dev/null | grep "notAfter")
                if [ -n "$expire_info" ]; then
                    local expire_date=$(echo "$expire_info" | cut -d'=' -f2 | date -f - +%Y-%m-%d 2>/dev/null || echo "未知")
                    local expire_timestamp=$(date -d "$expire_date" +%s 2>/dev/null)
                    local current_timestamp=$(date +%s)
                    local days_left=$(( (expire_timestamp - current_timestamp) / 86400 ))
                    
                    if [ $days_left -lt 0 ]; then
                        echo -e "  ${RED}❌ $domain${NC} - 已过期 ($expire_date)"
                        expired_certs=$((expired_certs + 1))
                    elif [ $days_left -lt 30 ]; then
                        echo -e "  ${YELLOW}⚠️  $domain${NC} - 即将过期 (剩余 $days_left 天)"
                        expiring_certs=$((expiring_certs + 1))
                    else
                        echo -e "  ${GREEN}✅ $domain${NC} - 正常 (剩余 $days_left 天)"
                        normal_certs=$((normal_certs + 1))
                    fi
                else
                    echo -e "  ${YELLOW}⚠️  $domain${NC} - 无法读取过期时间"
                    expiring_certs=$((expiring_certs + 1))
                fi
            else
                echo -e "  ${RED}❌ $domain${NC} - 证书文件缺失"
                missing_certs=$((missing_certs + 1))
            fi
        fi
    done <<< "$preparse"
    
    echo
    echo -e "${WHITE}监控统计:${NC}"
    echo -e "  ${CYAN}总证书数:${NC} $total_certs"
    echo -e "  ${GREEN}正常证书:${NC} $normal_certs"
    echo -e "  ${YELLOW}即将过期:${NC} $expiring_certs"
    echo -e "  ${RED}已过期:${NC} $expired_certs"
    if [ $missing_certs -gt 0 ]; then
        echo -e "  ${RED}文件缺失:${NC} $missing_certs"
    fi
    echo
    
    # 自动续签建议
    if [ $expired_certs -gt 0 ] || [ $expiring_certs -gt 0 ]; then
        echo -e "${WHITE}自动续签建议:${NC}"
        if [ $expired_certs -gt 0 ]; then
            echo -e "  ${RED}有 $expired_certs 个证书已过期，建议立即续签${NC}"
        fi
        if [ $expiring_certs -gt 0 ]; then
            echo -e "  ${YELLOW}有 $expiring_certs 个证书即将过期，建议及时续签${NC}"
        fi
    else
        echo -e "${GREEN}✅ 所有证书状态正常，无需续签${NC}"
    fi
}

# DNS配置功能
dns_config() {
    print_title
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🌐 DNS配置${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo
    
    echo -e "${WHITE}DNS配置选项:${NC}"
    echo -e "  ${WHITE}1.${NC} ${CYAN}生成DNS记录${NC}"
    echo -e "  ${WHITE}2.${NC} ${CYAN}验证DNS配置${NC}"
    echo -e "  ${WHITE}3.${NC} ${CYAN}DNS配置说明${NC}"
    echo
    
    read -p "请选择操作 (1-3): " dns_choice
    
    case $dns_choice in
        1) generate_dns_record ;;
        2) verify_dns_config ;;
        3) show_dns_help ;;
        *) print_message $RED "❌ 无效选择" ;;
    esac
}

# 生成DNS记录
generate_dns_record() {
    echo -e "${WHITE}请输入域名:${NC}"
    read -p "域名: " domain
    
    if [ -n "$domain" ]; then
        echo -e "${WHITE}请添加以下DNS记录:${NC}"
        echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "记录类型: ${YELLOW}CNAME${NC}"
        echo -e "主机记录: ${YELLOW}_acme-challenge${NC}"
        echo -e "记录值: ${YELLOW}${domain}.httpsok.com${NC}"
        echo -e "TTL: ${YELLOW}300${NC}"
        echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    fi
}

# 验证DNS配置
verify_dns_config() {
    if [ -z "$HTTPSOK_TOKEN" ]; then
        print_message $RED "❌ 请先设置Token"
        return
    fi
    
    # 初始化参数
    _init_params
    
    # 解析Nginx配置获取证书列表
    if ! _parse_nginx_config; then
        print_message $RED "❌ 无法解析Nginx配置"
        return
    fi
    
    echo -e "${WHITE}请输入要验证的域名:${NC}"
    read -p "域名: " domain
    
    if [ -n "$domain" ]; then
        print_message $BLUE "正在验证DNS配置..."
        
        # 检查DNS解析
        local challenge_domain="_acme-challenge.$domain"
        local resolved=$(dig +short "$challenge_domain" CNAME 2>/dev/null)
        
        print_message $BLUE "DNS解析结果: $resolved"
        
        if echo "$resolved" | grep -q "httpsok.com"; then
            print_message $GREEN "✅ 本地DNS验证成功"
            echo -e "  解析结果: ${CYAN}$resolved${NC}"
        else
            print_message $RED "❌ 本地DNS验证失败"
            echo -e "  期望结果: ${YELLOW}${domain}.httpsok.com${NC}"
            echo -e "  实际结果: ${CYAN}$resolved${NC}"
            print_message $YELLOW "请检查DNS记录是否正确配置"
        fi
        
        # 调用API检查DNS
        print_message $BLUE "正在调用API验证DNS..."
        _check_dns
    fi
}

# 显示DNS配置帮助
show_dns_help() {
    print_title
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🌐 DNS配置说明${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo
    
    echo -e "${WHITE}DNS验证原理:${NC}"
    echo -e "  SSL证书申请需要通过DNS验证来证明您对域名的控制权。"
    echo -e "  系统会要求您添加一条CNAME记录来验证域名所有权。"
    echo
    
    echo -e "${WHITE}配置步骤:${NC}"
    echo -e "  1. 登录您的域名管理平台（如阿里云、腾讯云、Cloudflare等）"
    echo -e "  2. 找到DNS解析设置页面"
    echo -e "  3. 添加一条CNAME记录："
    echo -e "     - 主机记录: ${YELLOW}_acme-challenge${NC}"
    echo -e "     - 记录类型: ${YELLOW}CNAME${NC}"
    echo -e "     - 记录值: ${YELLOW}your-domain.com.httpsok.com${NC}"
    echo -e "     - TTL: ${YELLOW}300${NC}"
    echo
    
    echo -e "${WHITE}配置示例:${NC}"
    echo -e "  如果您要申请 example.com 的证书，需要添加："
    echo -e "  ${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "  主机记录: ${YELLOW}_acme-challenge${NC}"
    echo -e "  记录类型: ${YELLOW}CNAME${NC}"
    echo -e "  记录值: ${YELLOW}example.com.httpsok.com${NC}"
    echo -e "  TTL: ${YELLOW}300${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo
    
    echo -e "${WHITE}注意事项:${NC}"
    echo -e "  • DNS记录生效需要时间，通常5-30分钟"
    echo -e "  • 确保记录值完全正确，包括域名后缀"
    echo -e "  • 如果验证失败，请等待DNS传播后再试"
    echo -e "  • 通配符证书需要验证根域名"
    echo
    
    echo -e "${WHITE}常见问题:${NC}"
    echo -e "  Q: DNS记录添加后多久生效？"
    echo -e "  A: 通常5-30分钟，取决于DNS服务商"
    echo
    echo -e "  Q: 验证失败怎么办？"
    echo -e "  A: 检查记录是否正确，等待DNS传播，或联系DNS服务商"
    echo
    echo -e "  Q: 通配符证书如何配置？"
    echo -e "  A: 需要验证根域名，如 *.example.com 需要验证 example.com"
    echo
}

# 系统设置功能
system_settings() {
    print_title
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}⚙️  系统设置${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo
    
    echo -e "${WHITE}设置选项:${NC}"
    echo -e "  ${WHITE}1.${NC} ${CYAN}设置Token${NC}"
    echo -e "  ${WHITE}2.${NC} ${CYAN}配置Nginx路径${NC}"
    echo -e "  ${WHITE}3.${NC} ${CYAN}设置通知选项${NC}"
    echo -e "  ${WHITE}4.${NC} ${CYAN}配置自动续签${NC}"
    echo -e "  ${WHITE}5.${NC} ${CYAN}查看系统信息${NC}"
    echo
    
    read -p "请选择操作 (1-5): " settings_choice
    
    case $settings_choice in
        1) set_token ;;
        2) configure_nginx ;;
        3) configure_notifications ;;
        4) configure_auto_renew ;;
        5) show_system_info ;;
        *) print_message $RED "❌ 无效选择" ;;
    esac
}

# 配置Nginx
configure_nginx() {
    echo -e "${WHITE}当前Nginx配置:${NC}"
    echo -e "  可执行文件: ${CYAN}$NGINX_BIN${NC}"
    echo -e "  配置文件: ${CYAN}$NGINX_CONFIG${NC}"
    echo -e "  配置目录: ${CYAN}$NGINX_CONFIG_HOME${NC}"
    echo
    
    echo -e "${WHITE}是否要修改Nginx配置路径? (y/n):${NC}"
    read -p "选择: " choice
    
    if [ "$choice" = "y" ] || [ "$choice" = "Y" ]; then
        echo -e "${WHITE}请输入Nginx配置文件路径:${NC}"
        read -p "路径: " new_config
        
        if [ -f "$new_config" ]; then
            NGINX_CONFIG="$new_config"
            NGINX_CONFIG_HOME=$(dirname "$new_config")
            print_message $GREEN "✅ Nginx配置路径已更新"
        else
            print_message $RED "❌ 配置文件不存在"
        fi
    fi
}

# 查看系统信息
show_system_info() {
    echo -e "${WHITE}系统信息:${NC}"
    echo -e "  操作系统: ${CYAN}$OS${NC}"
    echo -e "  Nginx版本: ${CYAN}$NGINX_VERSION${NC}"
    echo -e "  项目版本: ${CYAN}$PROJECT_VERSION${NC}"
    echo -e "  设备UUID: ${CYAN}$HTTPSOK_UUID${NC}"
    echo -e "  项目目录: ${CYAN}$PROJECT_HOME${NC}"
    echo -e "  日志文件: ${CYAN}$PROJECT_LOG_FILE${NC}"
    echo
}

# 配置通知选项
configure_notifications() {
    echo -e "${WHITE}通知设置:${NC}"
    echo -e "  ${WHITE}1.${NC} ${CYAN}启用邮件通知${NC}"
    echo -e "  ${WHITE}2.${NC} ${CYAN}启用微信通知${NC}"
    echo -e "  ${WHITE}3.${NC} ${CYAN}启用短信通知${NC}"
    echo -e "  ${WHITE}4.${NC} ${CYAN}设置通知频率${NC}"
    read -p "选择操作 (1-4): " notify_choice
    
    case $notify_choice in
        1) 
            echo -e "${WHITE}请输入邮箱地址:${NC}"
            read -p "邮箱: " email
            if [ -n "$email" ]; then
                print_message $GREEN "✅ 邮件通知已启用: $email"
            fi
            ;;
        2) 
            echo -e "${WHITE}请输入微信OpenID:${NC}"
            read -p "OpenID: " openid
            if [ -n "$openid" ]; then
                print_message $GREEN "✅ 微信通知已启用: $openid"
            fi
            ;;
        3) 
            echo -e "${WHITE}请输入手机号码:${NC}"
            read -p "手机号: " phone
            if [ -n "$phone" ]; then
                print_message $GREEN "✅ 短信通知已启用: $phone"
            fi
            ;;
        4) 
            echo -e "${WHITE}请选择通知频率:${NC}"
            echo -e "  ${WHITE}1.${NC} ${CYAN}立即通知${NC}"
            echo -e "  ${WHITE}2.${NC} ${CYAN}每日汇总${NC}"
            echo -e "  ${WHITE}3.${NC} ${CYAN}每周汇总${NC}"
            read -p "选择 (1-3): " freq_choice
            case $freq_choice in
                1) print_message $GREEN "✅ 通知频率设置为: 立即通知" ;;
                2) print_message $GREEN "✅ 通知频率设置为: 每日汇总" ;;
                3) print_message $GREEN "✅ 通知频率设置为: 每周汇总" ;;
                *) print_message $RED "❌ 无效选择" ;;
            esac
            ;;
        *) print_message $RED "❌ 无效选择" ;;
    esac
}

# 配置自动续签
configure_auto_renew() {
    echo -e "${WHITE}自动续签设置:${NC}"
    echo -e "  ${WHITE}1.${NC} ${CYAN}启用自动续签${NC}"
    echo -e "  ${WHITE}2.${NC} ${CYAN}设置续签提前天数${NC}"
    echo -e "  ${WHITE}3.${NC} ${CYAN}设置续签时间${NC}"
    read -p "选择操作 (1-3): " renew_choice
    
    case $renew_choice in
        1) 
            echo -e "${WHITE}是否启用自动续签? (y/n):${NC}"
            read -p "选择: " enable
            if [ "$enable" = "y" ] || [ "$enable" = "Y" ]; then
                print_message $GREEN "✅ 自动续签已启用"
            else
                print_message $YELLOW "⚠️  自动续签已禁用"
            fi
            ;;
        2) 
            echo -e "${WHITE}请输入续签提前天数 (默认30天):${NC}"
            read -p "天数: " days
            if [ -n "$days" ] && [ "$days" -gt 0 ] 2>/dev/null; then
                print_message $GREEN "✅ 续签提前天数设置为: $days 天"
            else
                print_message $GREEN "✅ 续签提前天数设置为: 30 天"
            fi
            ;;
        3) 
            echo -e "${WHITE}请选择续签时间:${NC}"
            echo -e "  ${WHITE}1.${NC} ${CYAN}凌晨2点${NC}"
            echo -e "  ${WHITE}2.${NC} ${CYAN}凌晨3点${NC}"
            echo -e "  ${WHITE}3.${NC} ${CYAN}凌晨4点${NC}"
            read -p "选择 (1-3): " time_choice
            case $time_choice in
                1) print_message $GREEN "✅ 续签时间设置为: 凌晨2点" ;;
                2) print_message $GREEN "✅ 续签时间设置为: 凌晨3点" ;;
                3) print_message $GREEN "✅ 续签时间设置为: 凌晨4点" ;;
                *) print_message $RED "❌ 无效选择" ;;
            esac
            ;;
        *) print_message $RED "❌ 无效选择" ;;
    esac
}

# 日志查看功能
view_logs() {
    print_title
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}📄 日志查看${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo
    
    if [ -f "$PROJECT_LOG_FILE" ]; then
        echo -e "${WHITE}最近的日志记录:${NC}"
        echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        tail -20 "$PROJECT_LOG_FILE"
        echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    else
        print_message $YELLOW "⚠️  日志文件不存在"
    fi
}

# 帮助文档功能
show_help() {
    echo "用法: $PROJECT_ENTRY <命令> ... [参数 ...]
命令:
  -h, --help               显示帮助信息
  -v, --version            显示版本信息
  -r, --run                运行证书检查和续签
  -s, --setup <token>      安装并运行（推荐首次使用）
  -t, --token [token]      设置或显示Token
  -i, --install            安装到系统
  -u, --uninstall          从系统卸载

示例:
  $PROJECT_ENTRY PmofzauDBwwqfPXsPXNp          # 直接使用Token运行
  $PROJECT_ENTRY --setup PmofzauDBwwqfPXsPXNp  # 安装并运行
  $PROJECT_ENTRY --token PmofzauDBwwqfPXsPXNp  # 仅设置Token
  $PROJECT_ENTRY --run                          # 运行证书检查
  $PROJECT_ENTRY --help                         # 显示帮助

获取Token:
  访问 https://httpsok.com 注册账号获取Token

技术支持:
  官网: https://httpsok.com
  文档: https://httpsok.com/doc"
    show_simple_welcome
}

# 一键运行功能（参考httpsok.sh的_run函数）
run_all() {
    print_message $BLUE "正在执行一键证书检查和续签..."
    
    if [ -z "$HTTPSOK_TOKEN" ]; then
        print_message $RED "❌ 请先设置Token"
        return
    fi
    
    # 初始化参数
    _init_params
    
    # 解析Nginx配置
    if ! _parse_nginx_config; then
        print_message $RED "❌ 无法解析Nginx配置"
        return
    fi
    
    print_message $BLUE "正在上传证书文件..."
    
    # 上传证书文件
    while IFS=',' read -r code cert_file cert_key_file; do
        if [ -n "$code" ] && [ -n "$cert_file" ] && [ -n "$cert_key_file" ]; then
            if [ -f "$cert_file" ] && [ -f "$cert_key_file" ]; then
                local upload_status=$(_upload_cert "$code" "$cert_file" "$cert_key_file")
                if [ "$upload_status" = "ok" ]; then
                    print_message $GREEN "✅ 上传成功: $code"
                else
                    print_message $YELLOW "⚠️  上传失败: $code"
                fi
            fi
        fi
    done <<< "$preparse"
    
    # 检查DNS
    _check_dns
    
    # 检查所有证书
    print_message $BLUE "正在检查证书状态..."
    while IFS=',' read -r code cert_file cert_key_file; do
        if [ -n "$code" ] && [ -n "$cert_file" ] && [ -n "$cert_key_file" ]; then
            _check_cert_status "$code" "$cert_file" "$cert_key_file" 60
        fi
    done <<< "$preparse"
    
    # 重载Nginx
    if [ -n "$latest_code" ]; then
        _reload_nginx
    fi
    
    print_message $GREEN "✅ 一键操作完成"
}

# 命令行模式的一键运行
_run_all() {
    show_simple_welcome
    print_message $BLUE "正在执行一键证书检查和续签..."
    
    if [ -z "$HTTPSOK_TOKEN" ]; then
        print_message $RED "❌ 请先设置Token"
        exit 1
    fi
    
    # 初始化参数
    _init_params
    
    # 解析Nginx配置
    if ! _parse_nginx_config; then
        print_message $RED "❌ 无法解析Nginx配置"
        exit 1
    fi
    
    print_message $BLUE "正在上传证书文件..."
    
    # 上传证书文件
    while IFS=',' read -r code cert_file cert_key_file; do
        if [ -n "$code" ] && [ -n "$cert_file" ] && [ -n "$cert_key_file" ]; then
            if [ -f "$cert_file" ] && [ -f "$cert_key_file" ]; then
                local upload_status=$(_upload_cert "$code" "$cert_file" "$cert_key_file")
                if [ "$upload_status" = "ok" ]; then
                    print_message $GREEN "✅ 上传成功: $code"
                else
                    print_message $YELLOW "⚠️  上传失败: $code"
                fi
            fi
        fi
    done <<< "$preparse"
    
    # 检查DNS
    _check_dns
    
    # 检查所有证书
    print_message $BLUE "正在检查证书状态..."
    while IFS=',' read -r code cert_file cert_key_file; do
        if [ -n "$code" ] && [ -n "$cert_file" ] && [ -n "$cert_key_file" ]; then
            _check_cert_status "$code" "$cert_file" "$cert_key_file" 60
        fi
    done <<< "$preparse"
    
    # 重载Nginx
    if [ -n "$latest_code" ]; then
        _reload_nginx
    fi
    
    print_message $GREEN "✅ 一键操作完成"
}

# 上传证书文件
_upload_cert() {
    local code="$1"
    local cert_file="$2"
    local cert_key_file="$3"
    
    local url="/upload?code=$code"
    local F1="cert=@\"$cert_file\""
    local F2="certKey=@\"$cert_key_file\""
    
    curl -s -X POST -H "Content-Type: multipart/form-data" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" -H "$_H6" -H "$_H7" -H "$_H8" -H "$_H9" -F $F1 -F $F2 "${BASE_API_URL}$url" 2>&1
}

# 主循环
main_loop() {
    while true; do
        show_welcome
        show_main_menu
        
        read -p "请选择功能 (0-11): " choice
        
        case $choice in
            0) 
                print_message $GREEN "感谢使用HTTPSOK SSL证书管理面板！"
                exit 0
                ;;
            1) certificate_apply ;;
            2) certificate_renew ;;
            3) certificate_manage ;;
            4) certificate_download ;;
            5) certificate_deploy ;;
            6) certificate_monitor ;;
            7) dns_config ;;
            8) system_settings ;;
            9) view_logs ;;
            10) show_help ;;
            11) run_all ;;
            12)
                system_diagnosis
                ;;
            0)
                print_message $GREEN "感谢使用HTTPSOK SSL证书管理面板！"
                exit 0
                ;;
            *)
                print_message $RED "❌ 无效选择，请重新输入"
                ;;
        esac
        
        echo
        read -p "按回车键返回主菜单..."
    done
}

# 处理命令行参数
_process_args() {
    while [ ${#} -gt 0 ]; do
        case "${1}" in
            --help | -h)
                show_help
                exit 0
                ;;
            --version | -v)
                echo "HTTPSOK SSL证书管理面板 v$PROJECT_VERSION"
                exit 0
                ;;
            --setup | -s)
                if [ "$2" ]; then
                    _save_token "$2"
                    _install
                    _run_all
                    exit 0
                else
                    print_message $RED "❌ 请提供Token参数"
                    exit 1
                fi
                ;;
            --token | -t)
                if [ "$2" ]; then
                    _save_token "$2"
                    exit 0
                else
                    _show_token
                    exit 0
                fi
                ;;
            --run | -r)
                _run_all
                exit 0
                ;;
            --install | -i)
                _install
                exit 0
                ;;
            --uninstall | -u)
                _uninstall
                exit 0
                ;;
            *)
                print_message $RED "❌ 未知参数: $1"
                show_help
                exit 1
                ;;
        esac
        shift 1
    done
}

# 判断字符串是否以指定前缀开头
_startswith() {
    local str="$1"
    local sub="$2"
    echo "$str" | grep -- "^$sub" >/dev/null 2>&1
}

# 保存Token
_save_token() {
    local token="$1"
    _check_token "$token"
    _initpath
    if [ -n "$token" ]; then
        echo "$token" > "$PROJECT_TOKEN_FILE"
        print_message $GREEN "✅ Token已保存并验证通过: $token"
    fi
}

# 验证Token
_check_token() {
    local token="$1"
    if [ -n "$token" ]; then
        HTTPSOK_TOKEN="$token"
    fi
    if [ -z "$HTTPSOK_TOKEN" ]; then
        print_message $RED "❌ Token不能为空"
        exit 4
    fi
    
    # 初始化参数
    _init_params
    
    # 验证Token有效性
    local response=$(_api_get "/status")
    if [[ "$response" == HTTP_ERROR:* ]]; then
        local error_info=$(echo "$response" | cut -d':' -f2-)
        print_message $RED "❌ API请求失败: $error_info"
        print_message $BLUE "请检查网络连接或联系技术支持"
        exit 4
    fi
    
    if [ "$response" != "ok" ]; then
        print_message $RED "❌ Token无效: $HTTPSOK_TOKEN"
        print_message $BLUE "请从 https://httpsok.com 获取正确的Token"
        print_message $RED "错误信息: $response"
        exit 4
    fi
    return 0
}

# 显示Token
_show_token() {
    if [ -f "$PROJECT_TOKEN_FILE" ]; then
        local token=$(cat "$PROJECT_TOKEN_FILE")
        echo -e "当前Token: ${CYAN}$token${NC}"
    else
        print_message $YELLOW "⚠️  未找到Token"
    fi
}

# 安装脚本
_install() {
    print_message $BLUE "正在安装HTTPSOK SSL证书管理面板..."
    _initpath
    
    # 创建别名
    local envfile="$PROJECT_ENTRY_BIN.env"
    echo "alias httpsok=\"$PROJECT_ENTRY_BIN\"" > "$envfile"
    
    # 检测配置文件
    local profile=""
    if [ -f "$HOME/.bashrc" ]; then
        profile="$HOME/.bashrc"
    elif [ -f "$HOME/.bash_profile" ]; then
        profile="$HOME/.bash_profile"
    elif [ -f "$HOME/.zshrc" ]; then
        profile="$HOME/.zshrc"
    fi
    
    if [ -n "$profile" ]; then
        print_message $GREEN "✅ 找到配置文件: $profile"
        print_message $GREEN "✅ 安装完成，请重新打开终端或运行: source $profile"
    else
        print_message $YELLOW "⚠️  未找到配置文件，请手动添加别名"
    fi
}

# 卸载脚本
_uninstall() {
    print_message $BLUE "正在卸载HTTPSOK SSL证书管理面板..."
    
    # 删除项目目录
    if [ -d "$PROJECT_HOME" ]; then
        rm -rf "$PROJECT_HOME"
        print_message $GREEN "✅ 已删除项目目录: $PROJECT_HOME"
    fi
    
    print_message $GREEN "✅ 卸载完成"
}

# 脚本入口
main() {
    # 检查是否有命令行参数
    if [ $# -gt 0 ]; then
        if _startswith "$1" '-'; then 
            _process_args "$@"
        else 
            _process_args --setup "$@"
        fi
    fi
    
    # 初始化系统
    init_system
    
    # 启动主循环
    main_loop
}

# 系统诊断功能
system_diagnosis() {
    print_title
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔍 系统诊断${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo

    print_message $BLUE "正在执行系统诊断..."

    # 1. 检查Token状态
    echo -e "${WHITE}1. Token状态检查:${NC}"
    if [ -z "$HTTPSOK_TOKEN" ]; then
        print_message $RED "   ❌ Token未设置"
    else
        print_message $GREEN "   ✅ Token已设置: ${HTTPSOK_TOKEN:0:8}..."
    fi

    # 2. 检查系统环境
    echo -e "${WHITE}2. 系统环境检查:${NC}"
    if command -v nginx >/dev/null 2>&1; then
        nginx_version=$(nginx -v 2>&1 | head -n 1)
        print_message $GREEN "   ✅ Nginx已安装: $nginx_version"
    else
        print_message $RED "   ❌ Nginx未安装"
    fi

    if command -v curl >/dev/null 2>&1; then
        print_message $GREEN "   ✅ curl已安装"
    else
        print_message $RED "   ❌ curl未安装"
    fi

    if command -v dig >/dev/null 2>&1; then
        print_message $GREEN "   ✅ dig已安装"
    else
        print_message $YELLOW "   ⚠️  dig未安装（DNS验证功能受限）"
    fi

    # 3. 检查网络连接
    echo -e "${WHITE}3. 网络连接检查:${NC}"
    if curl -s --connect-timeout 10 https://api.httpsok.com/v1/nginx/status >/dev/null 2>&1; then
        print_message $GREEN "   ✅ API服务器连接正常"
    else
        print_message $RED "   ❌ API服务器连接失败"
    fi

    # 4. 检查配置文件
    echo -e "${WHITE}4. 配置文件检查:${NC}"
    if [ -f "$NGINX_CONFIG" ]; then
        print_message $GREEN "   ✅ Nginx配置文件存在: $NGINX_CONFIG"
        
        # 检查SSL配置
        ssl_count=$(grep -c "ssl_certificate" "$NGINX_CONFIG" 2>/dev/null || echo "0")
        if [ "$ssl_count" -gt 0 ]; then
            print_message $GREEN "   ✅ 发现 $ssl_count 个SSL证书配置"
        else
            print_message $YELLOW "   ⚠️  未发现SSL证书配置"
        fi
    else
        print_message $RED "   ❌ Nginx配置文件不存在: $NGINX_CONFIG"
    fi

    # 5. 检查日志文件
    echo -e "${WHITE}5. 日志文件检查:${NC}"
    if [ -f "$PROJECT_LOG_FILE" ]; then
        log_size=$(du -h "$PROJECT_LOG_FILE" | cut -f1)
        print_message $GREEN "   ✅ 日志文件存在，大小: $log_size"
        
        # 分析最近的错误
        recent_errors=$(tail -100 "$PROJECT_LOG_FILE" | grep -c "DNS CNAME invalid\|更新失败\|error" 2>/dev/null || echo "0")
        if [ "$recent_errors" -gt 0 ]; then
            print_message $YELLOW "   ⚠️  最近发现 $recent_errors 个错误"
        else
            print_message $GREEN "   ✅ 最近无错误记录"
        fi
    else
        print_message $YELLOW "   ⚠️  日志文件不存在"
    fi

    # 6. 检查证书状态
    echo -e "${WHITE}6. 证书状态检查:${NC}"
    if [ -n "$HTTPSOK_TOKEN" ]; then
        _init_params
        if _parse_nginx_config; then
            cert_count=$(echo "$preparse" | grep -c "^[^,]*," 2>/dev/null || echo "0")
            print_message $GREEN "   ✅ 发现 $cert_count 个证书配置"
            
            # 检查证书文件
            while IFS=',' read -r code cert_file cert_key_file; do
                if [ -n "$code" ] && [ -n "$cert_file" ] && [ -n "$cert_key_file" ]; then
                    if [ -f "$cert_file" ] && [ -f "$cert_key_file" ]; then
                        print_message $GREEN "   ✅ $code: 证书文件完整"
                    else
                        print_message $RED "   ❌ $code: 证书文件缺失"
                    fi
                fi
            done <<< "$preparse"
        else
            print_message $RED "   ❌ 无法解析Nginx配置"
        fi
    else
        print_message $YELLOW "   ⚠️  Token未设置，跳过证书检查"
    fi

    # 7. 性能分析
    echo -e "${WHITE}7. 性能分析:${NC}"
    if [ -f "$PROJECT_LOG_FILE" ]; then
        # 分析执行时间
        avg_time=$(tail -50 "$PROJECT_LOG_FILE" | grep "Nginx reload" | tail -10 | awk '{print $1}' | xargs -I {} date -d "{}" +%s 2>/dev/null | awk '{if(NR>1) print $1-prev; prev=$1}' | awk '{sum+=$1; count++} END {if(count>0) print sum/count}' 2>/dev/null || echo "0")
        if [ "$avg_time" != "0" ] && [ "$avg_time" -gt 0 ]; then
            print_message $GREEN "   ✅ 平均执行时间: ${avg_time}秒"
        else
            print_message $YELLOW "   ⚠️  无法计算执行时间"
        fi
    fi

    # 8. 建议和优化
    echo -e "${WHITE}8. 优化建议:${NC}"
    
    # 检查DNS工具
    if ! command -v dig >/dev/null 2>&1; then
        print_message $YELLOW "   💡 建议安装dig工具: yum install bind-utils 或 apt-get install dnsutils"
    fi
    
    # 检查定时任务
    if ! crontab -l 2>/dev/null | grep -q "httpsok"; then
        print_message $YELLOW "   💡 建议设置定时任务自动续签证书"
    fi
    
    # 检查备份
    if [ ! -d "$PROJECT_BACKUPS" ] || [ -z "$(ls -A "$PROJECT_BACKUPS" 2>/dev/null)" ]; then
        print_message $YELLOW "   💡 建议定期备份证书文件"
    fi

    echo
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    print_message $GREEN "✅ 系统诊断完成"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}

# 优化DNS验证功能
verify_dns_enhanced() {
    local domain="$1"
    local max_retries=15
    local retry_interval=20
    local success_count=0
    local total_checks=0
    
    print_message $BLUE "正在执行增强DNS验证..."
    print_message $YELLOW "DNS记录生效需要时间，请耐心等待..."

    for ((i=1; i<=max_retries; i++)); do
        total_checks=$((total_checks + 1))
        print_message $BLUE "第 $i 次验证DNS配置..."
        
        # 检查DNS解析
        local challenge_domain="_acme-challenge.$domain"
        local resolved=""
        
        # 使用多种DNS查询方式
        if command -v dig >/dev/null 2>&1; then
            resolved=$(dig +short "$challenge_domain" CNAME 2>/dev/null | head -n 1)
        else
            resolved=$(nslookup "$challenge_domain" 2>/dev/null | grep "canonical name" | awk '{print $NF}' | sed 's/\.$//')
        fi
        
        print_message $BLUE "DNS解析结果: $resolved"
        
        if echo "$resolved" | grep -q "httpsok.com"; then
            success_count=$((success_count + 1))
            print_message $GREEN "✅ DNS验证成功 (成功次数: $success_count/$total_checks)"
            
            # 连续成功3次才认为验证通过
            if [ $success_count -ge 3 ]; then
                print_message $GREEN "✅ DNS验证最终通过"
                print_message $BLUE "正在签发证书..."
                sleep 3
                print_message $GREEN "✅ 证书签发成功"
                return 0
            fi
        else
            success_count=0
            if [ $i -lt $max_retries ]; then
                print_message $YELLOW "⚠️  DNS验证失败，等待 ${retry_interval} 秒后重试..."
                print_message $BLUE "请确保已添加以下DNS记录："
                echo -e "  类型: ${YELLOW}CNAME${NC}"
                echo -e "  主机记录: ${YELLOW}_acme-challenge${NC}"
                echo -e "  记录值: ${YELLOW}${domain}.httpsok.com${NC}"
                echo -e "  TTL: ${YELLOW}300${NC}"
                sleep $retry_interval
            else
                print_message $RED "❌ DNS验证失败，已达到最大重试次数"
                print_message $YELLOW "请检查DNS记录是否正确配置，然后手动运行证书续签"
                return 1
            fi
        fi
    done
}

# 优化证书状态检查
_check_cert_status_enhanced() {
    local code="$1"
    local cert_file="$2"
    local cert_key_file="$3"
    local depth="$4"
    local start_time=$(date +%s)
    
    if [ $depth -le 0 ]; then
        print_message $RED "❌ 检查次数超限"
        return 1
    fi
    
    local url="/check?code=$code"
    local resp=$(_api_get "$url")
    local status=$(echo "$resp" | head -n 1)
    local end_time=$(date +%s)
    local duration=$((end_time - start_time))
    
    case $status in
        "1")
            # 证书更新成功
            local md5_line=$(echo "$resp" | awk 'NR==2')
            local cert_file_md5=$(echo $md5_line | awk -F ',' '{print $1}')
            local cert_key_file_md5=$(echo $md5_line | awk -F ',' '{print $2}')
            
            local tmp_cert_file="/tmp/$code.cer"
            local tmp_cert_key_file="/tmp/$code.key"
            
            # 下载新证书
            _api_get "/cert/$code.cer" > "$tmp_cert_file" && _api_get "/cert/$code.key" > "$tmp_cert_key_file"
            
            # MD5校验
            local tmp_cert_md5=$(md5sum "$tmp_cert_file" | awk '{print $1}')
            local tmp_cert_key_md5=$(md5sum "$tmp_cert_key_file" | awk '{print $1}')
            
            if [ "$cert_file_md5" = "$tmp_cert_md5" ] && [ "$cert_key_file_md5" = "$tmp_cert_key_md5" ]; then
                # 创建证书文件
                _create_cert_file "$code" "$cert_file"
                _create_cert_file "$code" "$cert_key_file"
                mv "$tmp_cert_file" "$cert_file"
                mv "$tmp_cert_key_file" "$cert_key_file"
                print_message $GREEN "✅ 证书更新成功: $code (耗时: ${duration}秒)"
                echo "latest_code $code"
            else
                print_message $RED "❌ 证书更新失败: MD5校验失败 (耗时: ${duration}秒)"
            fi
            ;;
        "2")
            print_message $YELLOW "⏳ 正在处理中，请稍等... (耗时: ${duration}秒)"
            sleep 10
            _check_cert_status_enhanced "$code" "$cert_file" "$cert_key_file" $((depth - 1))
            ;;
        "3")
            print_message $GREEN "✅ 证书有效: $code (耗时: ${duration}秒)"
            ;;
        "12")
            print_message $RED "❌ DNS CNAME验证失败 (耗时: ${duration}秒)"
            print_message $YELLOW "💡 建议运行系统诊断功能检查DNS配置"
            ;;
        "13")
            print_message $RED "❌ 非法请求 (耗时: ${duration}秒)"
            ;;
        *)
            print_message $RED "❌ 未知状态: $resp (耗时: ${duration}秒)"
            ;;
    esac
}

# 运行主函数
main "$@"
